package web

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	"net/http"
	"testPaper/common"
	"testPaper/model"
	"testPaper/response"
	"testPaper/util"
)

// Register 用户注册
func Register(c *gin.Context) {
	DB := common.GetDB()
	name := c.PostForm("name")
	telephone := c.PostForm("telephone")
	password := c.PostForm("password")

	if len(telephone) != 11 {
		response.Reponse(c, http.StatusOK, 422, nil, "手机号输入格式错误")
		return
	} else if len(password) < 6 {
		response.Reponse(c, http.StatusOK, 422, nil, "设置的密码不能小于6位")
		return
	}
	if len(name) == 0 {
		name = util.RandName()
	}

	//	查询数据库手机号是否已经被注册
	if isTelephoneExits(DB, telephone) {
		response.Reponse(c, http.StatusOK, 422, nil, "手机号已经被注册")
		return
	}
	//密码加密
	hasePassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		response.Reponse(c, http.StatusUnprocessableEntity, 422, nil, "密码加密失败")
		return
	}

	newAdmin := model.Admin{
		Name:      name,
		Password:  string(hasePassword),
		Telephone: telephone,
	}
	DB.Create(&newAdmin)
	response.Reponse(c, http.StatusOK, 200, nil, "注册成功")
	return
}

func isTelephoneExits(db *gorm.DB, telephone string) bool {
	var admin model.Admin
	db.Where("telephone = ?", telephone).First(&admin)
	if admin.ID != 0 {
		return true
	}
	return false
}
